import logging
import os
import time
import datetime
from PyQt5.QtCore import *
import PyQt5.sip

file_path_mac = os.getcwd() + '/'
file_path_win = os.getcwd() + '\\'

logfile_path_win = file_path_win + 'record\\'
originfile_path_win = file_path_win + 'origin\\'

logfile_path_mac = file_path_mac + 'record/'
originfile_path_mac = file_path_mac + 'origin/'

tag_time = 'time'
tag_data = 'data'
tag_type = 'type'

VALUE_TYPE_SEND = 0  # 发送的数据
VALUE_TYPE_RECEIVE = 1  # 接收的数据

TYPE_RECORD_CSV = 0  # 文件类型，csv
TYPE_RECORD_ORIGIN = 1  # 文件类型，原始文件


class Recorder(QThread):
    _has_init = False
    servo_system = {
        "elel_deg": 0.0,
        "elel_deg_back": 0.0,
        "eler_deg": 0.0,
        "eler_deg_back": 0.0,
        "aill_deg": 0.0,
        "aill_deg_back": 0.0,
        "ailr_deg": 0.0,
        "ailr_deg_back": 0.0,
        "rud_deg": 0.0,
        "rud_deg_back": 0.0,
        "trust_percent": 0.0,
        "trust_percent_back": 0.0,
        "breakl_percent": 0.0,
        "breakl_back_bar": 0.0,
        "breakr_percent": 0.0,
        "breakr_back_bar": 0.0,
        "frontwheel_deg": 0.0,
        "frontwheel_deg_back": 0.0,
        "flap_deg": 0.0,
        "flap_deg_back": 0.0
    }
    fcc_system = {
        "system_info": {
            "cpu_useage": 25,
            "fcc_start_sec": 600,
            "fly_start_sec": 500,
            "software_version": 1.0
        },
        "route_flight": {
            "airline_number": 1,
            "dot_number": 1,
            "dx_m": 0.0,
            "dy_m": 0.0,
            "dh_m": 0.0,
            "dpsi_deg": 0.0,
            "one_way_dot_num": 0  # 在线航点数	uint8	1~255
        },
        "control_cmd": {
            "phi_cmd_deg": 0.0,
            "theta_cmd_deg": 0.0,
            "height_cmd_m": 0.0,
            "psi_cmd_deg": 0.0,
            "heading_cmd_deg": 0.0,
            "speed_cmd_mps": 0.0,
            "speed_cmd_kmph": 0.0,
            "dv_int_theta_deg": 0.0,
            "dv_int_trust_deg": 0.0,
            "dh_int_theta_deg": 0.0,
            "dy_int_phi_deg": 0.0,
            "dtheta_int_ele_deg": 0.0,
            "dphi_int_ail_deg": 0.0,
            "Vcmd_taxi": 0.0  # 滑行决策速度
        },
        "control_mode": {
            "fcc_config_mode": 0,  # 飞控装订模式，滑行或飞行模式  1:滑行模式 0：飞行模式
            "is_in_taxi_mode": 0,  # 当前是否处于滑行模式 1-滑行中 0-不处于滑行状态
            "on_taxi_correct": 0,  # 1：纠偏（绿灯）0：（红灯）
            "vertical_fly_mode": 0,  # 纵向飞行模态 00:无定义 01:平飞 10:爬升 11:下滑
            "lateral_mode": 0,  # 横向飞行模态 00:无定义 01:直飞10:向左 11:向右
            "link_protect": 0,  # 1：链路保护开，0：链路保护关
            "on_way_fly_mode": 0,  # 在线航路飞行中 0-非在线航路飞行 1-在线航路飞行

            "fly_mode": 0,  # 000：人工引导模态 001：点号进入模态 010：航线飞行模态 011：盘旋模态
            # 100：归航模态 101：着陆模态 110：低空飞行模态 111：起飞模态

            "in_takeoff_mode": 0,  # 起飞状态： 1：起飞（绿灯） 0：（灰色）
            "in_land_mode": 0,  # 着陆状态： 1：着陆（绿灯） 0：（灰色）
            "nav_mode": 0,  # 00：指令遥控01：一维导航 10：二维导航 11：三维导航

            "pre_nav": 0,  # 预导航开关 1：预导航 0：未开启预导航
            "on_air": 0,  # 空地状态 1：空中（绿灯） 0：地面（红灯）
            "on_reset": 0,  # 复位状态 1：复位（绿灯） 0：（红灯）

            "engine_pre_stop": 0,  # 1：发动机预停车（绿灯）0：（红灯） 绿灯亮起时才响应停车指令
            "engine_ctrl_mode": 0,  # 油门控制模式 0：最小油门，1：起飞油门，2：爬升油门，
            # 3：巡航大油门，4：巡航中油门，5：巡航小油门，
            # 6：下滑大油门，7：下滑小油门，8：怠速油门，9：停车
            "emerge_return": 0,  # 状态字2-紧急返航指示	D2	1：紧急返航
            "takeoff_allowed": 0,  # 允许起飞状态（备用）1：禁止 0：允许
            "acts_fail": 0,  # 状态字6-舵系统故障状态（备用）	1：故障 0：正常
            "ahrs_invalid": 0,  # 状态字6-姿态数据故障（备用）	1：故障 0：正常
            "pos_invalid": 0,  # 状态字6-位置数据故障（备用）	1：故障 0：正常
            "alt_invalid": 0  # 状态字6-高度数据故障（备用）	1：故障 0：正常

        },
        "sensor_fusion": {
            "attitude_source": 0,  # 姿态信号源： 0：姿态源故障 1：主惯导 2：备惯导
            "theta_deg": 0.0,
            "phi_deg": 0.0,
            "heading_deg": 0.0,  # 航向角，机头指向
            "wx_dps": 0.0,
            "wy_dps": 0.0,
            "wz_dps": 0.0,
            "acc_x": 0.0,
            "acc_y": 0.0,
            "acc_z": 0.0,
            "navigation_source": 0,  # 导航信息源 11：主惯:10：备惯 01：飞控GPS 00：不定位
            "lon_deg": 0.0,
            "lat_deg": 0.0,
            "vd_mps": 0.0,
            "vi_mps": 0.0,
            "psi_deg": 0.0,  # 航迹角 速度方向
            "hdot_mps": 0.0,
            "height_source": 0,  # 高度信号源：0：高度源故障 1：主惯导 2：GPS 3：气压高度
            "altitude_m": 0.0,
            "ref_height_m": 0.0
        },
        "origin_airport_info": {
            "altitude_m": 0.0,
            "qnh_m": 0.0,
            "runway_lon1": 0.0,
            "runway_lat1": 0.0,
            "runway_lon2": 0.0,
            "runway_lat2": 0.0,
            "runway_psi": 0.0  # 跑道航向
        },
        "dest_airport_info": {
            "altitude_m": 0.0,
            "qnh_m": 0.0,
            "runway_lon1": 0.0,
            "runway_lat1": 0.0,
            "runway_lon2": 0.0,
            "runway_lat2": 0.0,
            "runway_psi": 0.0  # 跑道航向
        }
    }
    sensor_ins = {
        "mins_connect": 0,  # 状态字2-主惯导连通状态	D4	1：连通 0：断开
        "freq": 0,
        "ins_state": 0,  # 0：INS未启动 1：INS对准模式 2：INS导航模式，但方位精度偏低
        # 3：INS高精度导航模式 6：INS导航模式，但GNSS可能故障 7：INS刚进入导航模式
        # 8：INS正在进行重力对准 9：等待初始定位估计，以开始对准
        "utc_time_year": 0,
        "utc_time_month": 0,
        "utc_time_day": 0,
        "utc_time_hour": 0,
        "utc_time_min": 0,
        "utc_time_sec": 0,
        "state_vel": 0.0,
        "state_pos": 0.0,  # 50 NARROW_INT  51 RTK_DIRECT_INS 52 INS_SBAS
        # 53 INS_PSRSP  54 INS_PSRDIFF  55 INS_RTKFLOAT
        # 56 INS_RTKFIXED 其他：显示数字
        "wx_dps": 0.0,
        "wy_dps": 0.0,
        "wz_dps": 0.0,
        "acc_x": 0.0,
        "acc_y": 0.0,
        "acc_z": 0.0,
        "vd_n_mps": 0.0,
        "vd_e_mps": 0.0,
        "vd_up_mps": 0.0,
        "hdot_mps": 0.0,
        "vd_mps": 0.0,
        "theta_deg": 0.0,
        "phi_deg": 0.0,
        "psi_deg": 0.0,
        "heading_deg": 0.0,
        "lon_deg": 0.0,
        "lat_deg": 0.0,
        "sat_used": 0.0,
        "sat_tracked": 0.0,
        "gdop": 0.0,
        "pdop": 0.0,
        "hdop": 0.0,
        "vdop": 0.0,
        "tdop": 0.0
    }
    sensor_bins = {
        "bins_connect": 0,  # 状态字2-备用惯导连通状态	D7	1：连通 0：断开
        "freq": 0,
        "gama_deg": 0.0,
        "theta_deg": 0.0,
        "psi_deg": 0.0,
        "acc_x": 0.0,
        "acc_y": 0.0,
        "acc_z": 0.0,
        "wx_dps": 0.0,
        "wy_dps": 0.0,
        "wz_dps": 0.0
    }
    sensor_adc = {
        "adc_connect": 0,  # 状态字2-大气机连通状态	D3	1：连通 0：断开
        "freq": 0,
        "adc_ram_error": 0,  # 大气机-RAM数据自检故障标志 1-无效 0-有效 1*/
        "adc_mach_invalid": 0,  # 大气机-马赫数无效标志 1-无效 0-有效 */
        "adc_hdot_invalid": 0,  # 大气机-升降速度无效标志 1-无效 0-有效 */
        "adc_vi_invalid": 0,  # 大气机-指示空速无效标志 1-无效 0-有效 */
        "adc_height_invalid": 0,  # 大气机-气压高度无效标志 1-无效 0-有效 */
        "adc_total_press_invalid": 0,  # 大气机-总压故障标志 1-无效 0-有效 */
        "adc_static_press_invalid": 0,  # 大气机-静压故障标志 1-无效 0-有效 */
        "adc_normal": 0,  # 大气机是否正常标志 1-正常 0-故障 */
        "height_m": 0.0,
        "vi_mps": 0.0,
        "mach": 0.0,
        "hdot_mps": 0.0,
    }
    sensor_adc2 = {
        "adc2_ssw_PS": 0,  # 大气机2状态字-静压状态	0:无效 1:有效	压力范围在0~103Kpa之间数据有效
        "adc2_ssw_QC": 0,  # 大气机2状态字-动压状态	0:无效 1:有效	压力范围在0~34Kpa之间数据有效
        "adc2_ssw_height": 0,  # 大气机2状态字-气压高度状态	0:无效 1:有效	范围在-305~12000m之间数据有效
        "adc2_ssw_hdot": 0,  # 大气机2状态字-升降速度状态	0:无效 1:有效	范围在-229~229m/s之间数据有效
        "adc2_ssw_SAT": 0,  # 大气机2状态字-静温状态	0:无效 1:有效	温度范围在-55~85℃之间数据有效
        "adc2_ssw_OAT": 0,  # 大气机2状态字-总温状态	0:无效 1:有效	温度范围在-55~85℃之间数据有效
        "adc2_ssw_mach": 0,  # 大气机2状态字-马赫数状态	0:无效 1:有效
        "adc2_ssw_vi": 0,  # 大气机2状态字-指示空速状态	0:无效 1:有效	范围在0~229m/s之间数据有效
        "adc2_ssw_va": 0,  # 大气机2状态字-真空速状态	0:无效 1:有效	范围在0~462m/s之间数据有效
        "adc2_ssw_heat": 0,  # 大气机2状态字-加热状态	0:自动加热 1:强制加热 2:强制不加热
        "adc2_ssw_alpha0": 0,  # 大气机2状态字-迎角	0:无效 1:有效	范围在-90~90°之间，且通讯正常时，数据有效
        "adc2_ssw_beta0": 0,  # 大气机2状态字-侧滑角0	0:无效 1:有效	范围在-90~90°之间，且通讯正常时，数据有效
        "adc2_ssw_alpha1": 0,  # 大气机2状态字-迎角1	0:无效 1:有效	范围在-90~90°之间，且通讯正常时，数据有效
        "adc2_ssw_beta1": 0,  # 大气机2状态字-侧滑角1	0:无效 1:有效	范围在-90~90°之间，且通讯正常时，数据有效
        "adc2_warn_low_temp": 0,  # 大气机2告警字-设备低温告警	0:正常 1:告警	当环境温度低于设备最低工作温度(-40℃)告警
        "adc2_warn_high_temp": 0,  # 大气机2告警字-设备高温告警	0:正常 1:告警	当环境温度高于设备最高工作温度(+65℃)告警
        "adc2_warn_low_vel": 0,  # 大气机2告警字-工作电压低告警	0:正常 1:告警	当供电电压低于设备最低工作电压(+9V)告警
        "adc2_warn_high_vel": 0,  # 大气机2告警字-工作电压高告警	0:正常 1:告警	当供电电压高于设备最高工作电压(+36V)告警
        "adc2_warn_heat1": 0,  # 大气机2告警字-加热1温度告警	0:正常 1:告警	当加热棒温度超出设定温度范围±20℃告警
        "adc2_warn_heat2": 0,  # 大气机2告警字-加热2温度告警	0:正常 1:告警	当加热棒温度超出设定温度范围±20℃告警
        "adc2_warn_heat3": 0,  # 大气机2告警字-加热3温度告警	0:正常 1:告警	预留，默认0
        "adc2_error_alpha0_invalid": 0,  # 大气机2故障字-迎角0传感器	0:正常 1:故障	迎角0状态字报故
        "adc2_error_beta0_invalid": 0,  # 大气机2故障字-侧滑角0传感器	0:正常 1:故障	侧滑角0状态字报故
        "adc2_error_alpha0_loss": 0,  # 大气机2故障字-迎角0通讯故障	0:正常 1:故障	迎角0无应答
        "adc2_error_beta0_loss": 0,  # 大气机2故障字-侧滑角通讯故障	0:正常 1:故障	侧滑角0无应答
        "adc2_error_QC_loss": 0,  # 大气机2故障字-动压传感器	0:正常 1:故障	接口采集超时，无应答
        "adc2_error_PS_loss": 0,  # 大气机2故障字-静压传感器	0:正常 1:故障	接口采集超时，无应答
        "adc2_error_OAT_invalid": 0,  # 大气机2故障字-总温传感器	0:正常 1:故障	温度超出测量范围-55~85℃
        "adc2_error_heat1_invalid": 0,  # 大气机2故障字-加热1温度传感器	0:正常 1:故障	温度超出测量范围-55~300℃
        "adc2_error_heat2_invalid": 0,  # 大气机2故障字-加热2温度传感器	0:正常 1:故障	温度超出测量范围-55~300℃
        "adc2_error_heat3_invalid": 0,  # 大气机2故障字-加热3温度传感器	0:正常 1:故障	预留，默认0
        "adc2_error_beta1_invalid": 0,  # 大气机2故障字-侧滑角1传感器	0:正常 1:故障	侧滑角1状态字报故
        "adc2_error_alpha1_invalid": 0,  # 大气机2故障字-迎角1传感器	0:正常 1:故障	迎角1无应答
        "adc2_error_beta1_loss": 0,  # 大气机2故障字-侧滑角1通讯故障	0:正常 1:故障	侧滑角1无应答
        "adc2_height": 0.0,  # 大气机2气压高度	-1000~4000	1	m
        "adc2_hdot": 0.0,  # 大气机2升降速度	-3276.8~3276.7	0.1	m/s
        "adc2_vi": 0.0,  # 大气机2指示空速	0~230	0.1	m/s
        "adc2_PS": 0.0,  # 大气机2静压	0~103350	1	pa
        "adc2_QC": 0.0,  # 大气机2动压	0~34470	1	pa
        "adc2_SAT": 0.0,  # 大气机2静温	-60~85	0.01	deg
        "adc2_TAT": 0.0,  # 大气机2总温	-60~85	0.01	deg
        "adc2_alpha0": 0.0,  # 大气机2迎角0	-180~180	0.01	deg
        "adc2_alpha1": 0.0,  # 大气机2迎角1	-180~180	0.01	deg
        "adc2_beta0": 0.0,  # 大气机2侧滑角0	-180~180	0.01	deg
        "adc2_beta1": 0.0,  # 大气机2侧滑角1	-180~180	0.01	deg
        "adc2_TAS": 0.0,  # 大气机2真空速	-3276.8~3276.7	0.1	m/s
        "adc2_mach": 0.0,  # 大气机2马赫数	0~3.2767	0.001
        "adc2_heat1temp": 0.0,  # 大气机2加热1温度	-128~127	3	deg
        "adc2_heat2temp": 0.0,  # 大气机2加热2温度	-128~127	3	deg
        "adc2_deg_temp": 0.0,  # 大气机2设备温度	-128~127	1	deg
        "adc2_dev_vol": 0.0,  # 大气机2设备工作电压	9~36	0.2	V
        "adc2_wds_vol": 0.0  # 大气机2风标供电电压	5V	0.05	V
    }
    sensor_radar = {
        "radar3_connect": 0,  # 状态字6-雷达3连通状态	1：连通 0：断开
        "radar2_connect": 0,  # 状态字6-雷达2连通状态	1：连通 0：断开
        "radar1_connect": 0,  # 状态字6-雷达1连通状态	1：连通 0：断开
        "radar0_alt_m": 0,
        "radar0_amp": 0,
        "radar0_freq": 0,
        "radar1_alt_m": 0,
        "radar1_amp": 0,
        "radar1_freq": 0,
        "radar2_alt_m": 0,
        "radar2_amp": 0,
        "radar2_freq": 0,
        "ac_radar_alt": 0.0,
        "valid_radar_num": 3
    }
    sensor_gps = {
        "freq": 0,
        "lon_deg": 0.0,
        "lat_deg": 0.0,
        "vd_mps": 0.0,
        "heading_deg": 0.0,
        "altitude_m": 0.0,
        "hdot_mps": 0.0,
        "sat_used": 0.0,
        "sat_tracked": 0.0,
        "gps_state": 0.0
    }
    datalink = {
        "llink_connect": 0,  # 状态字2-L数据链连通状态	D1	1：连通 0：断开
        "ulink_connect": 0,  # 状态字2-U数据链连通状态	D5	1：连通 0：断开
        "l_link_upload_freq": 0,
        "u_link_upload_freq": 0,
        "g_link_upload_freq": 0,
        "download_freq": 0,
        "current_link_type": "L"  # 当前链路类型 L-链路 U-链路 G-卫星通信链路
    }
    warnning_system = {
        "warnning_code": 0,
        "warnning_level": 0,
        "warnning_info_msg": "message string",
        "warinning_time": "02/02/14-15:53:59",
    }
    command_echo = {
        "echo_cmd_code": 0,  # 接收到的命令编号
        "echo_remote_code": 0,  # 命令反馈
        "echo_cmd_msg": "message string",
        "way_dot_num": 0,  # 当前处理的航点号
        "way_dot_lon": 0.0,  # 航点经度
        "way_dot_lat": 0.0,  # 航点纬度
        "way_dot_alt": 0.0,  # 航点高度
        "way_dot_vxd": 0  # 航点任务字
    }
    elec_system = {
        "elec_connect": 0,  # 状态字2-配电盒连通状态	D8	1：连通 0：断开
        "elec_freq": 0,  # EMU帧频
        "DI0_bin": 0,
        "DI1_bin": 0,
        "DO0_bin": 0,
        "DO1_bin": 0,
        "elec_cur_bat": 0,  # 蓄电池电流
        "elec_volA": 0,  # 汇流条A电压
        "elec_curA": 0,  # 汇流条A电流
        "elec_volB": 0,  # 汇流条B电压
        "elec_curB": 0,  # 汇流条B电流
        "elec_volC": 0,  # 14V汇流条电压
        "elec_curC": 0,  # 14V汇流条电流
        "elec_emerge_power": 0,  # 配电盒-应急电源开启状态 0:未接通，1:接通
        "elec_ground_power": 0,  # 配电盒-地面电源上电指示 0:未接通，1:接通
        "elec_aux_pump_on": 0,  # 配电盒-辅油泵开启状态 0:未接通，1:接通
        "elec_brake_power_on": 0,  # 配电盒-刹车电磁阀开启状态 0:未接通，1:接通
        "elec_circuit_B_on": 0  # 配电盒-B路可控输出开启状态(空速管加热) 0:未接通，1:接通
    }
    engine_system = {
        "emu_connect": 0.0,  # 状态字2-EMU连通状态	D6	1：连通 0：断开
        "trust_percent": 0.0,
        "rpm": 0,
        "press_air_hpa": 0.0,
        "press_env_hpa": 0.0,
        "temp_air_degree": 0.0,
        "pos_servo_percent": 0.0,
        "press_cor_psi": 0.0,
        "temp_cor_degree": 0.0,
        "press_limit_psi": 0.0,
        "temp_cyl2_degree": 0.0,
        "temp_cyl3_degree": 0.0,
        "temp_lube_degree": 0.0,
        "press_lube_bar": 0.0,
        "eng_vol_v": 0.0,
        "temp_gen1_degree": 0.0,
        "temp_gen2_degree": 0.0,
        "lamp_boost": 0.0,
        "lamp_alarm": 0.0,
        "status_boost": 0,
        "status_switch": 0,
        "error": 0,
        "press_qg_hpa": 0.0,
        "press_fuel_psi": 0.0,
        "fuel_right_l": 0.0,
        "fuel_left_l": 0.0,
        "temp_gas1_degree": 0.0,
        "temp_gas2_degree": 0.0,
        "temp_gas3_degree": 0.0,
        "temp_gas4_degree": 0.0,
        "start_time_hour": 0,
        "start_time_min": 0,
        "start_time_sec": 0,
        "total_time_hour": 0,
        "total_time_min": 0,
        "total_time_sec": 0,
        "emu_freq": 0.0,
        "tank_selection": 0  # 油箱选择 0-关闭 1-左油箱 2-右油箱
    }
    command_send = {
        "CmdType": 1,  # 1 - 代表地面站遥控指令 2 - 代表地检软件遥控指令
        "isControlCmd": 0,  # 当前指令是否为遥控指令 1 - 遥控指令，0 - 非遥控指令
        "ControlCmd": 0,  # 遥控指令编号，见协议中遥控指令表格
        "isAdjustCmd": 0,  # 当前指令是否为遥调指令 1 - 遥调指令，0 - 非遥调指令
        "AdjustCmd": 0,  # 遥调指令编号，见协议中遥调指令表格
        "AdjustCmdData": 0.0,  # 遥调指令数据，见协议中遥调指令表格

        # 在线航线上传数据
        "on_way_dot": 0,  # 航点号
        "on_way_lon": 0,  # 航点经度
        "on_way_lat": 0,  # 航点纬度
        "on_way_alt": 0,  # 航点高度
        "on_way_vxd": 0,  # 航点任务字

        # 驶入驶出航线上传数据
        "taxi_way_dot": 0,  # 航点号
        "taxi_way_lon": 0,  # 航点经度
        "taxi_way_lat": 0,  # 航点纬度
        "taxi_way_radious": 0,  # 转弯半径
        "RemoteCode": 0  # 回传指令，用于和下行数据中的回传指令对比
    }
    equipment = {
        "vhf_freq": 0,
        "vhf_demod_threshold": 0.0
    }

    def __new__(cls, *args, **kwargs):
        if not hasattr(Recorder, '_instance'):
            Recorder._instance = QThread.__new__(cls)
        return Recorder._instance

    def __init__(self):
        if not Recorder._has_init:
            Recorder._has_init = True
            super().__init__()
            self.working = True
            self.csv_rec_file = None  # 记录csv的
            self.rec_orign_file = None  # 记录原始数据的

            # 记录最后一次出现的a到e帧数据，用于数据填充
            self.dic_current_data = {'A': None, 'B': None, 'C': None, 'D': None, 'E': None, 'F': None}

            self.buffer_arr = []  # 数据缓冲区，元素是dict{'time':time, 'data':[]}，一个元素是1秒内收到的数据
            # 原始数据缓冲区，元素是dict{'time':time, 'type':0/1, 'data':hexstr}，同时记录收发，随记随写，不限制几秒内写一次
            self.orign_buffer_arr = []
            self.current_time = None  # 记录时间
            self.lock = QMutex()

    def stop_record(self):
        self.working = False
        self._close_file()

    def start_record(self):
        # 开始记录一个文件，之前不存在文件创建，如果存在正在写的文件，自动关闭，并且新建
        self.working = True
        self._close_file()

        current = os.getcwd()
        filepath = logfile_path_win
        origin_filepath = originfile_path_win
        if current.startswith('/'):
            filepath = logfile_path_mac
            origin_filepath = logfile_path_mac

        if not os.path.exists(filepath):
            os.makedirs(filepath)

        if not os.path.exists(origin_filepath):
            os.makedirs(origin_filepath)

        filename = time.strftime('%Y-%m-%d_%H-%M-%S') + '.csv'
        origin_filename = filename  # 飞行记录文件和原始文件保持一致的名称，不同目录
        try:
            self.csv_rec_file = open(filepath + filename, 'w', encoding='UTF-8')
            # 写入表头
            # A:31+9  B:27+3  C:17+3  D:40  E:36+4  F:17+3  大气机状态
            head = 'Time,Time_Year,Time_Mon,Time_Day,Time_Hour,Time_Min,Time_Sec,,elel_deg,elel_deg_back,eler_deg,' \
                   'eler_deg_back,aill_deg,aill_deg_back,ailr_deg,ailr_deg_back,rud_deg,rud_deg_back,trust_percent,' \
                   'trust_percent_back,breakl_percent,breakl_back_bar,breakr_percent,breakr_back_bar,frontwheel_deg,' \
                   'frontwheel_deg_back,flap_deg,flap_deg_back,sys_info_cpu_useage,sys_info_fcc_start_sec,' \
                   'sys_info_fly_start_sec,sys_info_software_version,route_airline_number,route_dot_number,' \
                   'route_dx_m,route_dy_m,route_dh_m,route_dpsi_deg,route_one_way_dot_num,ctrl_cmd_phi_cmd_deg,' \
                   'ctrl_cmd_theta_cmd_deg,ctrl_cmd_height_cmd_m,ctrl_cmd_psi_cmd_deg,ctrl_cmd_heading_cmd_deg,' \
                   'ctrl_cmd_speed_cmd_mps,ctrl_cmd_speed_cmd_kmph,ctrl_cmd_dv_int_theta_deg,' \
                   'ctrl_cmd_dv_int_trust_deg,ctrl_cmd_dh_int_theta_deg,ctrl_cmd_dy_int_phi_deg,' \
                   'ctrl_cmd_dtheta_int_ele_deg,ctrl_cmd_dphi_int_ail_deg,ctrl_cmd_Vcmd_taxi,' \
                   'ctrl_mode_fcc_config_mode,ctrl_mode_is_in_taxi_mode,ctrl_mode_on_taxi_correct,' \
                   'ctrl_mode_vertical_fly_mode,ctrl_mode_lateral_mode,ctrl_mode_link_protect,' \
                   'ctrl_mode_on_way_fly_mode,ctrl_mode_fly_mode,ctrl_mode_in_takeoff_mode,ctrl_mode_in_land_mode,' \
                   'ctrl_mode_nav_mode,ctrl_mode_pre_nav,ctrl_mode_on_air,ctrl_mode_on_reset,' \
                   'ctrl_mode_engine_pre_stop,ctrl_mode_engine_ctrl_mode,ctrl_mode_emerge_return,' \
                   'ctrl_mode_takeoff_allowed,ctrl_mode_acts_fail,ctrl_mode_ahrs_invalid,ctrl_mode_pos_invalid,' \
                   'ctrl_mode_alt_invalid,sensor_fusion_attitude_source,sensor_fusion_theta_deg,' \
                   'sensor_fusion_phi_deg,sensor_fusion_heading_deg,sensor_fusion_wx_dps,sensor_fusion_wy_dps,' \
                   'sensor_fusion_wz_dps,sensor_fusion_acc_x,sensor_fusion_acc_y,sensor_fusion_acc_z,' \
                   'sensor_fusion_navigation_source,sensor_fusion_lon_deg,sensor_fusion_lat_deg,sensor_fusion_vd_mps,' \
                   'sensor_fusion_vi_mps,sensor_fusion_psi_deg,sensor_fusion_hdot_mps,sensor_fusion_height_source,' \
                   'sensor_fusion_altitude_m,sensor_fusion_ref_height_m,org_apt_altitude_m,org_apt_qnh_m,' \
                   'org_apt_runway_lon1,org_apt_runway_lat1,org_apt_runway_lon2,org_apt_runway_lat2,' \
                   'org_apt_runway_psi,dst_apt_altitude_m,dst_apt_qnh_m,dst_apt_runway_lon1,dst_apt_runway_lat1,' \
                   'dst_apt_runway_lon2,dst_apt_runway_lat2,dst_apt_runway_psi,mins_connect,mins_freq,mins__state,' \
                   'mins_utc_time_year,mins_utc_time_month,mins_utc_time_day,mins_utc_time_hour,mins_utc_time_min,' \
                   'mins_utc_time_sec,mins_state_vel,mins_state_pos,mins_wx_dps,mins_wy_dps,mins_wz_dps,mins_acc_x,' \
                   'mins_acc_y,mins_acc_z,mins_vd_n_mps,mins_vd_e_mps,mins_vd_up_mps,mins_hdot_mps,mins_vd_mps,' \
                   'mins_theta_deg,mins_phi_deg,mins_psi_deg,mins_heading_deg,mins_lon_deg,mins_lat_deg,' \
                   'mins_sat_used,mins_sat_tracked,mins_gdop,mins_pdop,mins_hdop,mins_vdop,mins_tdop,bins_connect,' \
                   'bins_freq,bins_gama_deg,bins_theta_deg,bins_psi_deg,bins_acc_x,bins_acc_y,bins_acc_z,bins_wx_dps,' \
                   'bins_wy_dps,bins_wz_dps,adc_connect,adc_freq,adc_ram_error,adc_mach_invalid,adc_hdot_invalid,' \
                   'adc_vi_invalid,adc_height_invalid,adc_total_press_invalid,adc_static_press_invalid,adc_normal,' \
                   'adc_height_m,adc_vi_mps,adc_mach,adc_hdot_mps,adc2_ssw_PS,adc2_ssw_QC,adc2_ssw_height,' \
                   'adc2_ssw_hdot,adc2_ssw_SAT,adc2_ssw_OAT,adc2_ssw_mach,adc2_ssw_vi,adc2_ssw_va,adc2_ssw_heat,' \
                   'adc2_ssw_alpha0,adc2_ssw_beta0,adc2_ssw_alpha1,adc2_ssw_beta1,adc2_warn_low_temp,' \
                   'adc2_warn_high_temp,adc2_warn_low_vel,adc2_warn_high_vel,adc2_warn_heat1,adc2_warn_heat2,' \
                   'adc2_warn_heat3,adc2_error_alpha0_invalid,adc2_error_beta0_invalid,adc2_error_alpha0_loss,' \
                   'adc2_error_beta0_loss,adc2_error_QC_loss,adc2_error_PS_loss,adc2_error_OAT_invalid,' \
                   'adc2_error_heat1_invalid,adc2_error_heat2_invalid,adc2_error_heat3_invalid,' \
                   'adc2_error_beta1_invalid,adc2_error_alpha1_invalid,adc2_error_beta1_loss,adc2_height,adc2_hdot,' \
                   'adc2_vi,adc2_PS,adc2_QC,adc2_SAT,adc2_TAT,adc2_alpha0,adc2_alpha1,adc2_beta0,adc2_beta1,adc2_TAS,' \
                   'adc2_mach,adc2_heat1temp,adc2_heat2temp,adc2_deg_temp,adc2_dev_vol,adc2_wds_vol,radar3_connect,' \
                   'radar2_connect,radar1_connect,radar0_alt_m,radar0_amp,radar0_freq,radar1_alt_m,radar1_amp,' \
                   'radar1_freq,radar2_alt_m,radar2_amp,radar2_freq,ac_radar_alt,valid_radar_num,gps_freq,' \
                   'gps_lon_deg,gps_lat_deg,gps_vd_mps,gps_heading_deg,gps_altitude_m,gps_hdot_mps,gps_sat_used,' \
                   'gps_sat_tracked,gps_state,datalink_llink_connect,datalink_ulink_connect,' \
                   'datalink_l_link_upload_freq,datalink_u_link_upload_freq,datalink_g_link_upload_freq,' \
                   'datalink_download_freq,datalink_current_link_type,elec_connect,elec_freq,DI0_bin,DI1_bin,DO0_bin,' \
                   'DO1_bin,elec_cur_bat,elec_volA,elec_curA,elec_volB,elec_curB,elec_volC,elec_curC,' \
                   'elec_emerge_power,elec_ground_power,elec_aux_pump_on,elec_brake_power_on,elec_circuit_B_on,' \
                   'emu_connect,emu_trust_percent,emu_rpm,emu_press_air_hpa,emu_press_env_hpa,emu_temp_air_degree,' \
                   'emu_pos_servo_percent,emu_press_cor_psi,emu_temp_cor_degree,emu_press_limit_psi,' \
                   'emu_temp_cyl2_degree,emu_temp_cyl3_degree,emu_temp_lube_degree,emu_press_lube_bar,emu_eng_vol_v,' \
                   'emu_temp_gen1_degree,emu_temp_gen2_degree,emu_lamp_boost,emu_lamp_alarm,emu_status_boost,' \
                   'emu_status_switch,emu_error,emu_press_qg_hpa,emu_press_fuel_psi,emu_fuel_right_l,emu_fuel_left_l,' \
                   'emu_temp_gas1_degree,emu_temp_gas2_degree,emu_temp_gas3_degree,emu_temp_gas4_degree,' \
                   'emu_start_time_hour,emu_start_time_min,emu_start_time_sec,emu_total_time_hour,emu_total_time_min,' \
                   'emu_total_time_sec,emu_freq,emu_tank_selection,warnning_code,warnning_level,warnning_info_msg,' \
                   'warinning_time,echo_cmd_code,echo_remote_code,echo_cmd_msg,echo_way_dot_num,echo_way_dot_lon,' \
                   'echo_way_dot_lat,echo_way_dot_alt,echo_way_dot_vxd,send_CmdType,send_isControlCmd,' \
                   'send_ControlCmd,send_isAdjustCmd,send_AdjustCmd,send_AdjustCmdData,send_on_way_dot,' \
                   'send_on_way_lon,send_on_way_lat,send_on_way_alt,send_on_way_vxd,send_taxi_way_dot,' \
                   'send_taxi_way_lon,send_taxi_way_lat,taxi_way_radious,send_RemoteCode,equip_vhf_freq,' \
                   'equip_vhf_demod_threshold\n '

            self.csv_rec_file.write(head)

            self.rec_orign_file = open(origin_filepath + origin_filename, 'w', encoding='UTF-8')
            self.rec_orign_file.write('Time,Type,Data\n')
            self.start()
        except BaseException as e:
            logging.error("file open failed" + repr(e))
            self._close_file()

    def _close_file(self, file_type=None):
        # 关闭当前正在写的文件，如果file_type为none则两个文件一起关闭，否则只关闭一个
        try:
            if file_type == TYPE_RECORD_CSV:
                if self.csv_rec_file:
                    self.csv_rec_file.close()
                    self.csv_rec_file = None
            elif file_type == TYPE_RECORD_ORIGIN:
                if self.rec_orign_file:
                    self.rec_orign_file.close()
                    self.rec_orign_file = None
            else:
                if self.csv_rec_file:
                    self.csv_rec_file.close()
                    self.csv_rec_file = None
                if self.rec_orign_file:
                    self.rec_orign_file.close()
                    self.rec_orign_file = None
        except Exception as e:
            logging.error(repr(e))

    def _record_recv_data(self):
        # TODO:从datahandler获取接收到的数据
        # print("recording recv data")
        arr = []
        for i in range(350):
            arr.append('')
        arr[0] = '%.2f' % time.time()
        arr[1] = '%d' % time.localtime().tm_year
        arr[2] = '%d' % time.localtime().tm_mon
        arr[3] = '%d' % time.localtime().tm_mday
        arr[4] = '%d' % time.localtime().tm_hour
        arr[5] = '%d' % time.localtime().tm_min
        arr[6] = '%d' % time.localtime().tm_sec

        arr[8] = '%.2f' % self.servo_system['elel_deg']
        arr[9] = '%.2f' % self.servo_system['elel_deg_back']
        arr[10] = '%.2f' % self.servo_system['eler_deg']
        arr[11] = '%.2f' % self.servo_system['eler_deg_back']
        arr[12] = '%.2f' % self.servo_system['aill_deg']
        arr[13] = '%.2f' % self.servo_system['aill_deg_back']
        arr[14] = '%.2f' % self.servo_system['ailr_deg']
        arr[15] = '%.2f' % self.servo_system['ailr_deg_back']
        arr[16] = '%.2f' % self.servo_system['rud_deg']
        arr[17] = '%.2f' % self.servo_system['rud_deg_back']
        arr[18] = '%.2f' % self.servo_system['trust_percent']
        arr[19] = '%.2f' % self.servo_system['trust_percent_back']
        arr[20] = '%.2f' % self.servo_system['breakl_percent']
        arr[21] = '%.2f' % self.servo_system['breakl_back_bar']
        arr[22] = '%.2f' % self.servo_system['breakr_percent']
        arr[23] = '%.2f' % self.servo_system['breakr_back_bar']
        arr[24] = '%.2f' % self.servo_system['frontwheel_deg']
        arr[25] = '%.2f' % self.servo_system['frontwheel_deg_back']
        arr[26] = '%.2f' % self.servo_system['flap_deg']
        arr[27] = '%.2f' % self.servo_system['flap_deg_back']

        arr[28] = '%d' % self.fcc_system['system_info']["cpu_useage"]
        arr[29] = '%d' % self.fcc_system['system_info']["fcc_start_sec"]
        arr[30] = '%d' % self.fcc_system['system_info']["fly_start_sec"]
        arr[31] = '%d' % self.fcc_system['system_info']["software_version"]

        arr[32] = '%d' % self.fcc_system['route_flight']["airline_number"]
        arr[33] = '%d' % self.fcc_system['route_flight']["dot_number"]
        arr[34] = '%.2f' % self.fcc_system['route_flight']["dx_m"]
        arr[35] = '%.2f' % self.fcc_system['route_flight']["dy_m"]
        arr[36] = '%.2f' % self.fcc_system['route_flight']["dh_m"]
        arr[37] = '%.2f' % self.fcc_system['route_flight']["dpsi_deg"]
        arr[38] = '%d' % self.fcc_system['route_flight']["one_way_dot_num"]

        arr[39] = '%.2f' % self.fcc_system['control_cmd']["phi_cmd_deg"]
        arr[40] = '%.2f' % self.fcc_system['control_cmd']["theta_cmd_deg"]
        arr[41] = '%.2f' % self.fcc_system['control_cmd']["height_cmd_m"]
        arr[42] = '%.2f' % self.fcc_system['control_cmd']["psi_cmd_deg"]
        arr[43] = '%.2f' % self.fcc_system['control_cmd']["heading_cmd_deg"]
        arr[44] = '%.2f' % self.fcc_system['control_cmd']["speed_cmd_mps"]
        arr[45] = '%.2f' % self.fcc_system['control_cmd']["speed_cmd_kmph"]
        arr[46] = '%.2f' % self.fcc_system['control_cmd']["dv_int_theta_deg"]
        arr[47] = '%.2f' % self.fcc_system['control_cmd']["dv_int_trust_deg"]
        arr[48] = '%.2f' % self.fcc_system['control_cmd']["dh_int_theta_deg"]
        arr[49] = '%.2f' % self.fcc_system['control_cmd']["dy_int_phi_deg"]
        arr[50] = '%.2f' % self.fcc_system['control_cmd']["dtheta_int_ele_deg"]
        arr[51] = '%.2f' % self.fcc_system['control_cmd']["dphi_int_ail_deg"]
        arr[52] = '%.2f' % self.fcc_system['control_cmd']["Vcmd_taxi"]

        arr[53] = '%d' % self.fcc_system['control_mode']["fcc_config_mode"]
        arr[54] = '%d' % self.fcc_system['control_mode']["is_in_taxi_mode"]
        arr[55] = '%d' % self.fcc_system['control_mode']["on_taxi_correct"]
        arr[56] = '%d' % self.fcc_system['control_mode']["vertical_fly_mode"]
        arr[57] = '%d' % self.fcc_system['control_mode']["lateral_mode"]
        arr[58] = '%d' % self.fcc_system['control_mode']["link_protect"]
        arr[59] = '%d' % self.fcc_system['control_mode']["on_way_fly_mode"]
        arr[60] = '%d' % self.fcc_system['control_mode']["fly_mode"]
        arr[61] = '%d' % self.fcc_system['control_mode']["in_takeoff_mode"]
        arr[62] = '%d' % self.fcc_system['control_mode']["in_land_mode"]
        arr[63] = '%d' % self.fcc_system['control_mode']["nav_mode"]
        arr[64] = '%d' % self.fcc_system['control_mode']["pre_nav"]
        arr[65] = '%d' % self.fcc_system['control_mode']["on_air"]
        arr[66] = '%d' % self.fcc_system['control_mode']["on_reset"]
        arr[67] = '%d' % self.fcc_system['control_mode']["engine_pre_stop"]
        arr[68] = '%d' % self.fcc_system['control_mode']["engine_ctrl_mode"]
        arr[69] = '%d' % self.fcc_system['control_mode']["emerge_return"]
        arr[70] = '%d' % self.fcc_system['control_mode']["takeoff_allowed"]
        arr[71] = '%d' % self.fcc_system['control_mode']["acts_fail"]
        arr[72] = '%d' % self.fcc_system['control_mode']["ahrs_invalid"]
        arr[73] = '%d' % self.fcc_system['control_mode']["pos_invalid"]
        arr[74] = '%d' % self.fcc_system['control_mode']["alt_invalid"]

        arr[75] = '%d' % self.fcc_system['sensor_fusion']["attitude_source"]
        arr[76] = '%.2f' % self.fcc_system['sensor_fusion']["theta_deg"]
        arr[77] = '%.2f' % self.fcc_system['sensor_fusion']["phi_deg"]
        arr[78] = '%.2f' % self.fcc_system['sensor_fusion']["heading_deg"]
        arr[79] = '%.2f' % self.fcc_system['sensor_fusion']["wx_dps"]
        arr[80] = '%.2f' % self.fcc_system['sensor_fusion']["wy_dps"]
        arr[81] = '%.2f' % self.fcc_system['sensor_fusion']["wz_dps"]
        arr[82] = '%.2f' % self.fcc_system['sensor_fusion']["acc_x"]
        arr[83] = '%.2f' % self.fcc_system['sensor_fusion']["acc_y"]
        arr[84] = '%.2f' % self.fcc_system['sensor_fusion']["acc_z"]
        arr[85] = '%d' % self.fcc_system['sensor_fusion']["navigation_source"]
        arr[86] = '%.7f' % self.fcc_system['sensor_fusion']["lon_deg"]
        arr[87] = '%.7f' % self.fcc_system['sensor_fusion']["lat_deg"]
        arr[88] = '%.2f' % self.fcc_system['sensor_fusion']["vd_mps"]
        arr[89] = '%.2f' % self.fcc_system['sensor_fusion']["vi_mps"]
        arr[90] = '%.2f' % self.fcc_system['sensor_fusion']["psi_deg"]
        arr[91] = '%.2f' % self.fcc_system['sensor_fusion']["hdot_mps"]
        arr[92] = '%d' % self.fcc_system['sensor_fusion']["height_source"]
        arr[93] = '%.1f' % self.fcc_system['sensor_fusion']["altitude_m"]
        arr[94] = '%.1f' % self.fcc_system['sensor_fusion']["ref_height_m"]

        arr[95] = '%.1f' % self.fcc_system['origin_airport_info']['altitude_m']
        arr[96] = '%.1f' % self.fcc_system['origin_airport_info']['qnh_m']
        arr[97] = '%.7f' % self.fcc_system['origin_airport_info']['runway_lon1']
        arr[98] = '%.7f' % self.fcc_system['origin_airport_info']['runway_lat1']
        arr[99] = '%.7f' % self.fcc_system['origin_airport_info']['runway_lon2']
        arr[100] = '%.7f' % self.fcc_system['origin_airport_info']['runway_lat2']
        arr[101] = '%.1f' % self.fcc_system['origin_airport_info']['runway_psi']

        arr[102] = '%.1f' % self.fcc_system['dest_airport_info']['altitude_m']
        arr[103] = '%.1f' % self.fcc_system['dest_airport_info']['qnh_m']
        arr[104] = '%.7f' % self.fcc_system['dest_airport_info']['runway_lon1']
        arr[105] = '%.7f' % self.fcc_system['dest_airport_info']['runway_lat1']
        arr[106] = '%.7f' % self.fcc_system['dest_airport_info']['runway_lon2']
        arr[107] = '%.7f' % self.fcc_system['dest_airport_info']['runway_lat2']
        arr[108] = '%.1f' % self.fcc_system['dest_airport_info']['runway_psi']

        arr[109] = '%d' % self.sensor_ins['mins_connect']
        arr[110] = '%d' % self.sensor_ins['freq']
        arr[111] = '%d' % self.sensor_ins['ins_state']
        arr[112] = '%d' % self.sensor_ins['utc_time_year']
        arr[113] = '%d' % self.sensor_ins['utc_time_month']
        arr[114] = '%d' % self.sensor_ins['utc_time_day']
        arr[115] = '%d' % self.sensor_ins['utc_time_hour']
        arr[116] = '%d' % self.sensor_ins['utc_time_min']
        arr[117] = '%d' % self.sensor_ins['utc_time_sec']
        arr[118] = '%d' % self.sensor_ins['state_vel']
        arr[119] = '%d' % self.sensor_ins['state_pos']
        arr[120] = '%.2f' % self.sensor_ins['wx_dps']
        arr[121] = '%.2f' % self.sensor_ins['wy_dps']
        arr[122] = '%.2f' % self.sensor_ins['wz_dps']
        arr[123] = '%.2f' % self.sensor_ins['acc_x']
        arr[124] = '%.2f' % self.sensor_ins['acc_y']
        arr[125] = '%.2f' % self.sensor_ins['acc_z']
        arr[126] = '%.2f' % self.sensor_ins['vd_n_mps']
        arr[127] = '%.2f' % self.sensor_ins['vd_e_mps']
        arr[128] = '%.2f' % self.sensor_ins['vd_up_mps']
        arr[129] = '%.2f' % self.sensor_ins['hdot_mps']
        arr[130] = '%.2f' % self.sensor_ins['vd_mps']
        arr[131] = '%.2f' % self.sensor_ins['theta_deg']
        arr[132] = '%.2f' % self.sensor_ins['phi_deg']
        arr[133] = '%.2f' % self.sensor_ins['psi_deg']
        arr[134] = '%.2f' % self.sensor_ins['heading_deg']
        arr[135] = '%.7f' % self.sensor_ins['lon_deg']
        arr[136] = '%.7f' % self.sensor_ins['lat_deg']
        arr[137] = '%d' % self.sensor_ins['sat_used']
        arr[138] = '%d' % self.sensor_ins['sat_tracked']
        arr[139] = '%.2f' % self.sensor_ins['gdop']
        arr[140] = '%.2f' % self.sensor_ins['pdop']
        arr[141] = '%.2f' % self.sensor_ins['hdop']
        arr[142] = '%.2f' % self.sensor_ins['vdop']
        arr[143] = '%.2f' % self.sensor_ins['tdop']

        arr[144] = '%d' % self.sensor_bins['bins_connect']
        arr[145] = '%d' % self.sensor_bins['freq']
        arr[146] = '%.2f' % self.sensor_bins['gama_deg']
        arr[147] = '%.2f' % self.sensor_bins['theta_deg']
        arr[148] = '%.2f' % self.sensor_bins['psi_deg']
        arr[149] = '%.2f' % self.sensor_bins['acc_x']
        arr[150] = '%.2f' % self.sensor_bins['acc_y']
        arr[151] = '%.2f' % self.sensor_bins['acc_z']
        arr[152] = '%.2f' % self.sensor_bins['wx_dps']
        arr[153] = '%.2f' % self.sensor_bins['wy_dps']
        arr[154] = '%.2f' % self.sensor_bins['wz_dps']

        arr[155] = '%d' % self.sensor_adc['adc_connect']
        arr[156] = '%d' % self.sensor_adc['freq']
        arr[157] = '%d' % self.sensor_adc['adc_ram_error']
        arr[158] = '%d' % self.sensor_adc['adc_mach_invalid']
        arr[159] = '%d' % self.sensor_adc['adc_hdot_invalid']
        arr[160] = '%d' % self.sensor_adc['adc_vi_invalid']
        arr[161] = '%d' % self.sensor_adc['adc_height_invalid']
        arr[162] = '%d' % self.sensor_adc['adc_total_press_invalid']
        arr[163] = '%d' % self.sensor_adc['adc_static_press_invalid']
        arr[164] = '%d' % self.sensor_adc['adc_normal']
        arr[165] = '%.1f' % self.sensor_adc['height_m']
        arr[166] = '%.1f' % self.sensor_adc['vi_mps']
        arr[167] = '%.3f' % self.sensor_adc['mach']
        arr[168] = '%.1f' % self.sensor_adc['hdot_mps']

        arr[169] = '%d' % self.sensor_adc2['adc2_ssw_PS']
        arr[170] = '%d' % self.sensor_adc2['adc2_ssw_QC']
        arr[171] = '%d' % self.sensor_adc2['adc2_ssw_height']
        arr[172] = '%d' % self.sensor_adc2['adc2_ssw_hdot']
        arr[173] = '%d' % self.sensor_adc2['adc2_ssw_SAT']
        arr[174] = '%d' % self.sensor_adc2['adc2_ssw_OAT']
        arr[175] = '%d' % self.sensor_adc2['adc2_ssw_mach']
        arr[176] = '%d' % self.sensor_adc2['adc2_ssw_vi']
        arr[177] = '%d' % self.sensor_adc2['adc2_ssw_va']
        arr[178] = '%d' % self.sensor_adc2['adc2_ssw_heat']
        arr[179] = '%d' % self.sensor_adc2['adc2_ssw_alpha0']
        arr[180] = '%d' % self.sensor_adc2['adc2_ssw_beta0']
        arr[181] = '%d' % self.sensor_adc2['adc2_ssw_alpha1']
        arr[182] = '%d' % self.sensor_adc2['adc2_ssw_beta1']
        arr[183] = '%d' % self.sensor_adc2['adc2_warn_low_temp']
        arr[184] = '%d' % self.sensor_adc2['adc2_warn_high_temp']
        arr[185] = '%d' % self.sensor_adc2['adc2_warn_low_vel']
        arr[186] = '%d' % self.sensor_adc2['adc2_warn_high_vel']
        arr[187] = '%d' % self.sensor_adc2['adc2_warn_heat1']
        arr[188] = '%d' % self.sensor_adc2['adc2_warn_heat2']
        arr[189] = '%d' % self.sensor_adc2['adc2_warn_heat3']
        arr[190] = '%d' % self.sensor_adc2['adc2_error_alpha0_invalid']
        arr[191] = '%d' % self.sensor_adc2['adc2_error_beta0_invalid']
        arr[192] = '%d' % self.sensor_adc2['adc2_error_alpha0_loss']
        arr[193] = '%d' % self.sensor_adc2['adc2_error_beta0_loss']
        arr[194] = '%d' % self.sensor_adc2['adc2_error_QC_loss']
        arr[195] = '%d' % self.sensor_adc2['adc2_error_PS_loss']
        arr[196] = '%d' % self.sensor_adc2['adc2_error_OAT_invalid']
        arr[197] = '%d' % self.sensor_adc2['adc2_error_heat1_invalid']
        arr[198] = '%d' % self.sensor_adc2['adc2_error_heat2_invalid']
        arr[199] = '%d' % self.sensor_adc2['adc2_error_heat3_invalid']
        arr[200] = '%d' % self.sensor_adc2['adc2_error_beta1_invalid']
        arr[201] = '%d' % self.sensor_adc2['adc2_error_alpha1_invalid']
        arr[202] = '%d' % self.sensor_adc2['adc2_error_beta1_loss']
        arr[203] = '%.2f' % self.sensor_adc2['adc2_height']
        arr[204] = '%.2f' % self.sensor_adc2['adc2_hdot']
        arr[205] = '%.2f' % self.sensor_adc2['adc2_vi']
        arr[206] = '%.2f' % self.sensor_adc2['adc2_PS']
        arr[207] = '%.2f' % self.sensor_adc2['adc2_QC']
        arr[208] = '%.2f' % self.sensor_adc2['adc2_SAT']
        arr[209] = '%.2f' % self.sensor_adc2['adc2_TAT']
        arr[210] = '%.2f' % self.sensor_adc2['adc2_alpha0']
        arr[211] = '%.2f' % self.sensor_adc2['adc2_alpha1']
        arr[212] = '%.2f' % self.sensor_adc2['adc2_beta0']
        arr[213] = '%.2f' % self.sensor_adc2['adc2_beta1']
        arr[214] = '%.2f' % self.sensor_adc2['adc2_TAS']
        arr[215] = '%.2f' % self.sensor_adc2['adc2_mach']
        arr[216] = '%.2f' % self.sensor_adc2['adc2_heat1temp']
        arr[217] = '%.2f' % self.sensor_adc2['adc2_heat2temp']
        arr[218] = '%.2f' % self.sensor_adc2['adc2_deg_temp']
        arr[219] = '%.2f' % self.sensor_adc2['adc2_dev_vol']
        arr[220] = '%.2f' % self.sensor_adc2['adc2_wds_vol']

        arr[221] = '%d' % self.sensor_radar['radar3_connect']
        arr[222] = '%d' % self.sensor_radar['radar2_connect']
        arr[223] = '%d' % self.sensor_radar['radar1_connect']
        arr[224] = '%.1f' % self.sensor_radar['radar0_alt_m']
        arr[225] = '%d' % self.sensor_radar['radar0_amp']
        arr[226] = '%d' % self.sensor_radar['radar0_freq']
        arr[227] = '%.1f' % self.sensor_radar['radar1_alt_m']
        arr[228] = '%d' % self.sensor_radar['radar1_amp']
        arr[229] = '%d' % self.sensor_radar['radar1_freq']
        arr[230] = '%.1f' % self.sensor_radar['radar2_alt_m']
        arr[231] = '%d' % self.sensor_radar['radar2_amp']
        arr[232] = '%d' % self.sensor_radar['radar2_freq']
        arr[233] = '%.1f' % self.sensor_radar['ac_radar_alt']
        arr[234] = '%d' % self.sensor_radar['valid_radar_num']

        arr[235] = '%d' % self.sensor_gps['freq']
        arr[236] = '%.7f' % self.sensor_gps['lon_deg']
        arr[237] = '%.7f' % self.sensor_gps['lat_deg']
        arr[238] = '%.2f' % self.sensor_gps['vd_mps']
        arr[239] = '%.2f' % self.sensor_gps['heading_deg']
        arr[240] = '%.2f' % self.sensor_gps['altitude_m']
        arr[241] = '%.2f' % self.sensor_gps['hdot_mps']
        arr[242] = '%d' % self.sensor_gps['sat_used']
        arr[243] = '%d' % self.sensor_gps['sat_tracked']
        arr[244] = '%d' % self.sensor_gps['gps_state']

        arr[245] = '%d' % self.datalink['llink_connect']
        arr[246] = '%d' % self.datalink['ulink_connect']
        arr[247] = '%d' % self.datalink['l_link_upload_freq']
        arr[248] = '%d' % self.datalink['u_link_upload_freq']
        arr[249] = '%d' % self.datalink['g_link_upload_freq']
        arr[250] = '%d' % self.datalink['download_freq']
        arr[251] = self.datalink['current_link_type']

        arr[252] = '%d' % self.elec_system['elec_connect']
        arr[253] = '%d' % self.elec_system['elec_freq']
        arr[254] = '%d' % self.elec_system['DI0_bin']
        arr[255] = '%d' % self.elec_system['DI1_bin']
        arr[256] = '%d' % self.elec_system['DO0_bin']
        arr[257] = '%d' % self.elec_system['DO1_bin']
        arr[258] = '%.1f' % self.elec_system['elec_cur_bat']
        arr[259] = '%.1f' % self.elec_system['elec_volA']
        arr[260] = '%.1f' % self.elec_system['elec_curA']
        arr[261] = '%.1f' % self.elec_system['elec_volB']
        arr[262] = '%.1f' % self.elec_system['elec_curB']
        arr[263] = '%.1f' % self.elec_system['elec_volC']
        arr[264] = '%.1f' % self.elec_system['elec_curC']
        arr[265] = '%d' % self.elec_system['elec_emerge_power']
        arr[266] = '%d' % self.elec_system['elec_ground_power']
        arr[267] = '%d' % self.elec_system['elec_aux_pump_on']
        arr[268] = '%d' % self.elec_system['elec_brake_power_on']
        arr[269] = '%d' % self.elec_system['elec_circuit_B_on']

        arr[270] = '%d' % self.engine_system['emu_connect']
        arr[271] = '%.1f' % self.engine_system['trust_percent']
        arr[272] = '%d' % self.engine_system['rpm']
        arr[273] = '%.2f' % self.engine_system['press_air_hpa']
        arr[274] = '%.2f' % self.engine_system['press_env_hpa']
        arr[275] = '%d' % self.engine_system['temp_air_degree']
        arr[276] = '%.1f' % self.engine_system['pos_servo_percent']
        arr[277] = '%.1f' % self.engine_system['press_cor_psi']
        arr[278] = '%d' % self.engine_system['temp_cor_degree']
        arr[279] = '%.1f' % self.engine_system['press_limit_psi']
        arr[280] = '%d' % self.engine_system['temp_cyl2_degree']
        arr[281] = '%d' % self.engine_system['temp_cyl3_degree']
        arr[282] = '%d' % self.engine_system['temp_lube_degree']
        arr[283] = '%.1f' % self.engine_system['press_lube_bar']
        arr[284] = '%.1f' % self.engine_system['eng_vol_v']
        arr[285] = '%d' % self.engine_system['temp_gen1_degree']
        arr[286] = '%d' % self.engine_system['temp_gen2_degree']
        arr[287] = '%d' % self.engine_system['lamp_boost']
        arr[288] = '%d' % self.engine_system['lamp_alarm']
        arr[289] = '%d' % self.engine_system['status_boost']
        arr[290] = '%d' % self.engine_system['status_switch']
        arr[291] = '%d' % self.engine_system['error']
        arr[292] = '%.1f' % self.engine_system['press_qg_hpa']
        arr[293] = '%.1f' % self.engine_system['press_fuel_psi']
        arr[294] = '%.1f' % self.engine_system['fuel_right_l']
        arr[295] = '%.1f' % self.engine_system['fuel_left_l']
        arr[296] = '%d' % self.engine_system['temp_gas1_degree']
        arr[297] = '%d' % self.engine_system['temp_gas2_degree']
        arr[298] = '%d' % self.engine_system['temp_gas3_degree']
        arr[299] = '%d' % self.engine_system['temp_gas4_degree']
        arr[300] = '%d' % self.engine_system['start_time_hour']
        arr[301] = '%d' % self.engine_system['start_time_min']
        arr[302] = '%d' % self.engine_system['start_time_sec']
        arr[303] = '%d' % self.engine_system['total_time_hour']
        arr[304] = '%d' % self.engine_system['total_time_min']
        arr[305] = '%d' % self.engine_system['total_time_sec']
        arr[306] = '%d' % self.engine_system['emu_freq']
        arr[307] = '%d' % self.engine_system['tank_selection']

        arr[308] = '%d' % self.warnning_system['warnning_code']
        arr[309] = '%d' % self.warnning_system['warnning_level']
        arr[310] = self.warnning_system['warnning_info_msg']
        arr[311] = self.warnning_system['warinning_time']

        arr[312] = '%d' % self.command_echo['echo_cmd_code']
        arr[313] = '%d' % self.command_echo['echo_remote_code']
        arr[314] = self.command_echo['echo_cmd_msg']
        arr[315] = '%d' % self.command_echo['way_dot_num']
        arr[316] = '%.7f' % self.command_echo['way_dot_lon']
        arr[317] = '%.7f' % self.command_echo['way_dot_lat']
        arr[318] = '%.1f' % self.command_echo['way_dot_alt']
        arr[319] = '%d' % self.command_echo['way_dot_vxd']

        arr[320] = '%d' % self.command_send['CmdType']
        arr[321] = '%d' % self.command_send['isControlCmd']
        arr[322] = '%d' % self.command_send['ControlCmd']
        arr[323] = '%d' % self.command_send['isAdjustCmd']
        arr[324] = '%d' % self.command_send['AdjustCmd']
        arr[325] = '%d' % self.command_send['AdjustCmdData']
        arr[326] = '%d' % self.command_send['on_way_dot']
        arr[327] = '%.7f' % self.command_send['on_way_lon']
        arr[328] = '%.7f' % self.command_send['on_way_lat']
        arr[329] = '%.1f' % self.command_send['on_way_alt']
        arr[330] = '%d' % self.command_send['on_way_vxd']
        arr[331] = '%d' % self.command_send['taxi_way_dot']
        arr[332] = '%.7f' % self.command_send['taxi_way_lon']
        arr[333] = '%.7f' % self.command_send['taxi_way_lat']
        arr[334] = '%.2f' % self.command_send['taxi_way_radious']
        arr[335] = '%d' % self.command_send['RemoteCode']

        arr[336] = '%d' % self.equipment['vhf_freq']
        arr[337] = '%.1f' % self.equipment['vhf_demod_threshold']

        data_str = ','.join(arr) + '\n'
        try:
            self.csv_rec_file.write(data_str)
        except BaseException as e:
            logging.info(repr(e))
            self._close_file(TYPE_RECORD_CSV)

    def _record_send_data(self):
        # print("recording send data")
        # TODO:从datahandler获取发出的数据
        pass

    def run(self):
        while self.working:
            time.sleep(0.1)
            # self.lock.lock()
            try:
                self._record_recv_data()
                # self._record_send_data()
            except Exception as e:
                logging.error(repr(e))
            finally:
                # self.lock.unlock()
                pass

datarecoder = Recorder()

if __name__ == '__main__':
    r = Recorder()
    r.start_record()
